package br.com.upper.util;

import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import uk.ltd.getahead.dwr.WebContext;
import uk.ltd.getahead.dwr.WebContextFactory;
import br.com.upper.business.Facade;
import br.com.upper.entity.InstanceType;
import br.com.upper.entity.TestResult;



public class DWRController {

	static Logger logger = Logger.getLogger(DWRController.class);

	public DWRController() {

	}

	private HttpSession getSession() {
		WebContext wc = WebContextFactory.get();
		HttpSession session = null;
		if(wc != null) {
			session = wc.getSession();
		}
		return session;
	}

	private ServletContext getServletContext() {
		WebContext wc = WebContextFactory.get();
		ServletContext context = null;
		if(wc != null) {
			context = wc.getServletContext();
		}		
		return context;
	}
	
	public TestStatus checkTestStatus() {
		
		TestStatus status = TestManager.checkStatus();
		
		if(status.getCurrentStep() == TestStep.FINISHED) {
			long currentTime = System.currentTimeMillis();
			long initTotalTime = (Long)getSession().getAttribute("initTotalTime");
			long initTestTime = (Long)getSession().getAttribute("initTestTime");
			TestResult result = (TestResult) getSession().getAttribute("testResult");
			result.setEndTimestamp(new Date());
			result.setInstanceType(TestManager.bestInstance);
			result.setVolumeType(result.getVolumeTypePropposed());
			result.setProvisionedIOPs(result.getProvisionedIOPsProppoed());
			result.setTestTime((currentTime - initTestTime));
			result.setTotalTime((currentTime - initTotalTime));
			Facade.getInstance().saveTestResult(result);
		}
		
		return status;
	}
	
	public InstanceType getBestInstance() {
		return TestManager.bestInstance;
	}
	
}
